#include <iostream>
#include <memory>
#include <string>
#include <functional>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Udp_Server.hpp"
#include "Log.hpp"
#include "mythread.hpp"
#include "ThreadPool.hpp"
#include "Route.hpp"
using namespace ThreadClass;

int InitClient()
{
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        LOG(FATAL, "create socket errno!\n");
        exit(SERVER_ERROR);
    }
    return sockfd;
}
void RecvMessage(int sockfd, const std::string &name)
{
    while (true)
    {
        struct sockaddr_in perr;
        char buf[1024];
        socklen_t len = sizeof(perr);
        ssize_t n = recvfrom(sockfd, buf, sizeof(buf) - 1, 0, (struct sockaddr *)(&perr), &len);
        if (n > 0)
        {
            buf[n] = '\0';
            InetAddr who(perr);
            std::cout <<who.GetAddrStr()<<buf << std::endl;
        }
        else
        {
            std::cerr << "recvfrom error!\n"
                      << std::endl;
            break;
        }
    }
}
void SendMessage(int sockfd, std::string &ip, uint16_t port, const std::string &name)
{
    struct sockaddr_in src;
    memset(&src, 0, sizeof(src));
    src.sin_family = AF_INET;
    src.sin_addr.s_addr = inet_addr(ip.c_str());
    src.sin_port = htons(port);
    std::string client_prev = "SendThread# ";
    while (true)
    {
        std::string line;
        std::cout << client_prev;
        std::getline(std::cin, line);
        // send message;
        int n = sendto(sockfd, line.c_str(), line.size(), 0, (struct sockaddr *)(&src), sizeof(src));
        if (n <= 0)
        {
            std::cerr << "sendthread send error! \n"<< std::endl;
            break;
        }
    }
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "usage 3 nums_command-->[./name ip port]" << std::endl;
        exit(-1);
    }
    int sockfd = InitClient();
    std::string s_ip = argv[1];
    uint16_t port = std::stoi(argv[2]);
    // start threads
    Thread recever("recever-thread", std::bind(&RecvMessage, sockfd, std::placeholders::_1));
    Thread Sender("Sender-thread", std::bind(&SendMessage, sockfd, s_ip, port, std::placeholders::_1));
    recever.Start();
    Sender.Start();
    
    recever.Join();
    Sender.Join();

    ::close(sockfd);
    return 0;
}